package util;

import java.io.*;
import java.nio.charset.StandardCharsets;

public class FileOperationUtil {
    public static String fileDir = "D:\\SQL_data\\TicketManagementData\\info\\";

    public static void write(String path, String content) {
        try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(path), StandardCharsets.UTF_8)
        )) {
            // 若文件不存在，会自动创建文件
            writer.write(content);
        } catch (IOException e) {
            System.out.println("写入文件时发生错误：" + e.getMessage());
        }
    }

    public static String read(String path) {
        StringBuilder stringBuilder = new StringBuilder();
        try (BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8)
        )) {
            String temp;
            while ((temp = bufferedReader.readLine()) != null) {
                stringBuilder.append(temp).append("\n");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return stringBuilder.toString();
    }

    public static String changeTextName(String path, String textName) {
        File file = new File(path);
        String newFilePath = file.getParent() + "\\" + textName; // 新文件路径为原文件所在目录+新文件名
        File newFile = new File(newFilePath);

        if (!file.renameTo(newFile)){
            System.out.println("文件名修改失败");
        }

        return newFilePath;
    }

    public static void delete(String path) {
        File file = new File(path);
        if (file.delete()) {
            System.out.println("删除成功");
        }
        else {
            System.out.println("删除失败");
        }
    }
}
